package com.lemon.jvm.hotspot.src.share.tools;


import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

public class DataTranslate {

    private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    private static final CharsetDecoder decoder = Charset.forName("utf-8").newDecoder();

    public static final String bytesToUtf8String(byte[] bytes) {
        return new String(bytes, decoder.charset());
    }

    public static final String bytesToHex(byte[] bytes) {
        char[] chars = new char[bytes.length * 2];
        int p = 0;
        for (byte b : bytes) {
            chars[p++] = HEX_CHAR[(b >>> 4) & 0x0F];
            chars[p++] = HEX_CHAR[b & 0x0F];
        }
        return new String(chars);
    }

    public static int byteToUnsignedShort(byte[] bytes, int position) {
        int high = bytes[position];
        int low = bytes[position + 1];
        return (high << 8 & 0xFF00) | (low & 0xFF);
    }

    public static int byteToUnsignedShort(byte[] bytes) {
        int high = bytes[0];
        int low = bytes[1];
        return (high << 8 & 0xFF00) | (low & 0xFF);
    }

    public static int byteToInt(byte[] bytes) {
        return ((bytes[0] & 0xFF) << 24) |
                ((bytes[1] & 0xFF) << 16) |
                ((bytes[2] & 0xFF) << 8) |
                (bytes[3] & 0xFF);
    }
}
